package io.yunho.spring.boot.rocketmq.basic;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * @author: Jason
 * @date: 2021/4/12 14:42
 * @description:
 */
@Component
public class SpringProducer {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void sendMessage(String topic, String message) {
        rocketMQTemplate.convertAndSend(topic,message);
    }

    public void sendTransactionMessage(String topic, String message) throws InterruptedException {
        String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 0; i < 10; i++) {
            //尝试在Header中加入自定义的属性
                Message<String> msg = MessageBuilder.withPayload(message)
                        .setHeader(RocketMQHeaders.TRANSACTION_ID,"TransID_"+i)
                        //发到事务监听器里后,这个自已设定的TAGS属性会去失,但是上面那个属性不会丢失。
                        .setHeader(RocketMQHeaders.TAGS,tags[i % tags.length])
                        //MyGroup 在事务监听器里也可以拿到，为什么单单这个RocketMQHeaders.TAGS拿不到，看来得撸源码
                        .setHeader("MyGroup","MyGroup_"+i)
                        .build();
                String destination = topic+":"+tags[i % tags.length];
                //这里发送事务消息时，还是会转换成RocketMQ的message对象，再调用RocketMQ的原生API完成事务消息机制。
                SendResult sendResult = rocketMQTemplate.sendMessageInTransaction(destination,msg, destination);
                System.out.printf("%s%n", sendResult);

                Thread.sleep(10);
        }
    }
}
